<!-- 盛期调查 -->
<template>
	<view class="container">
		<view class="example">
			<!-- 基础用法，不包含校验规则 -->
			<uni-forms ref="baseForm" class="form-box" :model="surveyKh" labelWidth="125px">
				<uni-forms-item label="监测站点代码" required>
					<uni-easyinput v-model="surveyKh.ydNumber" :disabled="true" />
				</uni-forms-item>
				<uni-forms-item label="项目名称" required>
					<uni-easyinput v-model="surveyKh.projectName" :disabled="true" placeholder="请输入任务名称" />
				</uni-forms-item>
				<uni-forms-item label="样方编号" required>
					<uni-easyinput v-model="surveyKh.yfNumber" :disabled="true" />
				</uni-forms-item>
				<uni-forms-item label="经度" required>
					<uni-easyinput v-model="surveyKh.lon" :disabled="!isnew" />
				</uni-forms-item>
				<uni-forms-item label="纬度" required>
					<uni-easyinput v-model="surveyKh.lat" :disabled="!isnew" />
				</uni-forms-item>
				<uni-forms-item label="海拔">
					<uni-easyinput v-model="surveyKh.altitude" :disabled="!isnew"  placeholder="请输入海拔" />
				</uni-forms-item>
			<!-- 	<uni-forms-item label="植被覆盖">
					<uni-easyinput v-model="surveyKh.zbgd" :disabled="!isnew" placeholder="请输入植被覆盖" />
				</uni-forms-item> -->
				<uni-forms-item label="温度">
					<uni-easyinput v-model="surveyKh.temperature" :disabled="!isnew" placeholder="请输入温度" />
				</uni-forms-item>
				<uni-forms-item label="湿度">
					<uni-easyinput v-model="surveyKh.humidness" :disabled="!isnew" placeholder="请输入" />
				</uni-forms-item>
				<uni-forms-item label="植被总盖度">
					<uni-easyinput v-model="surveyKh.zbzgd" :disabled="!isnew" placeholder="请输入" />
				</uni-forms-item>
				<uni-forms-item label="枯黄植被盖度">
					<uni-easyinput v-model="surveyKh.khzbgd" :disabled="!isnew" placeholder="请输入%" />
				</uni-forms-item>
				<uni-forms-item label="植被枯黄百分率">
					<uni-easyinput style="float: left;" v-model="surveyKh.zbkhbfl" :disabled="!isnew"  placeholder="请输入%" />
				</uni-forms-item>
				<uni-forms-item label="枯黄植株平均高度">
					<uni-easyinput style="float: left;" v-model="surveyKh.khzwpjgd" :disabled="!isnew" placeholder="请输入cm" />
				</uni-forms-item>
				<uni-forms-item label="枯黄植物种数">
					<uni-easyinput style="float: left;" v-model="surveyKh.khzwzs" :disabled="!isnew" placeholder="请输入" />
				</uni-forms-item>
				<uni-forms-item label="优势植物名称">
					<uni-easyinput style="float: left;" v-model="surveyKh.khyszwmc" :disabled="!isnew" placeholder="请输入" />
				</uni-forms-item>
				<uni-forms-item label="枯黄植物名称">
					<uni-easyinput style="float: left;" v-model="surveyKh.khzwmc" :disabled="!isnew" placeholder="请输入" />
				</uni-forms-item>



				<uni-forms-item label="照片" class="uni-list list-pd">
					<view class="uni-list-cell cell-pd">
						<view class="uni-uploader">
							<view class="uni-uploader-body">
								<view class="uni-uploader__files">
									<block v-for="(image,index) in imageList" :key="index">
										<view class="uni-uploader__file">
											<image class="uni-uploader__img" :src="image" :data-src="image"
												@tap="previewImage"></image>
										</view>
									</block>
									<view class="uni-uploader__input-box">
										<view class="uni-uploader__input" @tap="chooseImage"></view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</uni-forms-item>



			</uni-forms>
			<button type="primary" @click="submit('valiForm')">{{title}}</button>

		</view>

		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="warn" cancelText="关闭" confirmText="确认" title="警告" content="确定删除该方案吗？"
				@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
		</uni-popup>

	</view>
</template>

<script>
	import {
		addOrUpdateYf,
		delYf
	} from '@/api/system.js'
	import {
		getInfo,
		setInfo
	} from '@/core/unicommon/storyageInfo.js'
	import {
		saveImage,
		uploadImage
	} from '@/core/file/File.js'
	import {
		getLocation
	} from '@/core/unicommon/deviceInfo.js'
	export default {
		data() {
			return {
				btns: [{
					name: "盖度",
					index: 0
				}, {
					name: "草地类型",
					index: 1
				}, {
					name: "生物量",
					index: 2
				}, {
					name: "温湿度",
					index: 3
				}],
				title: "提交",
				isnew: false,
				type: "creat",
				network: false,
				surveyKh: {
					"altitude": "",
					"createTime": "2023-12-06T13:41:52.517Z",
					"fqqyfzp": "",
					"fqyszwmc": "",
					"fqzbgd": "",
					"fqzbmc": "",
					"fqzbzs": "",
					"fqzzpjgd": "",
					"humidness": "",
					"khyfzp": "",
					"khyszwmc": "",
					"khzbgd": "",
					"khzwmc": "",
					"khzwpjgd": "",
					"khzwzs": "",
					"lat": "",
					"lon": "",
					"sqyfzp": "",
					"surveyType": "",
					"temperature": "",
					"updateTime": "2023-12-06T13:41:52.517Z",
					"ydNumber": "",
					"yfNumber": (new Date()).getFullYear() + "-",
					"zbfqbfl": "",
					"zbgd": "",
					"zbkhbfl": "",
					"zbzgd": ""
				},
				sourceTypeIndex: 2,
				sourceType: ['拍照', '相册', '拍照或相册'],
				sizeTypeIndex: 2,
				sizeType: ['压缩', '原图', '压缩或原图'],
				countIndex: 8,
				count: [1, 2, 3, 4, 5, 6, 7, 8, 9],
				// 基础表单数据

				imageList: [],
				// 城市数据
				cityData: [{
					text: "北京",
					value: "10001",
				}, {
					text: "上海",
					value: "10002",
				}, {
					text: "深圳",
					value: "10004",
				}],
				gravel: [{
						value: 0,
						text: "多"
					},
					{
						value: 1,
						text: "少"
					},
					{
						value: 2,
						text: "无"
					},
				],


				// 单选数据源
				ishas: [{
					text: '有',
					value: 0
				}, {
					text: '无',
					value: 1
				}],

				// 校验表单数据
				valiFormData: {
					name: '',
					age: '',
					introduction: '',
				},
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					age: {
						rules: [{
							required: true,
							errorMessage: '年龄不能为空'
						}, {
							format: 'number',
							errorMessage: '年龄只能输入数字'
						}]
					}
				},

			}
		},
		computed: {

		},
		onLoad(e) {

			if (e && e.data) {
				let data = JSON.parse(decodeURIComponent(e.data))
				this.surveyKh.ydNumber = data.ydNumber
				if (data.yfNumber) {

					this.surveyKh.yfNumber = data.yfNumber
					this.submited = true
					this.title = "编辑"
					this.isnew = false
				} else {
					this.surveyKh.action = "creat"
					this.surveyKh.yfNumber =  (new Date()).getTime()+""
					this.submited = false
					this.isnew = true
					this.title = "提交"
				}

			}

			getInfo("userdata").then(res => {
				this.userdata = res.data
				let yd = res.data.yd.find(t => t.ydNumber == this.surveyKh.ydNumber)

				let yf = res.data.yf.find(t => t.yfNumber == this.surveyKh.yfNumber)
				if (yf) {
					this.surveyKh = yf
				} else {
					this.surveyKh = this.createObject(this.surveyKh)
				}
				this.surveyKh.projectName = data.projectName
				
				let files = this.userdata.files
				this.imageList = []
				if (this.surveyKh.khyfzp) {
					let sqzp = JSON.parse(this.surveyKh.khyfzp)
					for (const zp of sqzp) {
						let localzp = files.find(t => t.type == 'yf' && t.uid == zp.uid)
						if (localzp) {
							this.imageList.push(localzp.localurl)
						}
					}
				}
				
			})


			if (!this.surveyKh.lat || this.surveyKh.lat == '') {
				getLocation().then(res => {
					this.surveyKh.lon = res.longitude
					this.surveyKh.lat = res.latitude
				})
			}
			this.surveyKh.createTime = new Date()
			this.surveyKh.surveyType = "枯黄期"
			this.getNetWork()
		},
		onReady() {
			// getInfo("network").then(res => {
			// 	this.network = res.data
			// })
			this.getNetWork()
		},
		methods: {
			getNetWork() {
				let that = this
				uni.getNetworkType({
					success: res => {
						if (res.networkType === 'none') {
							that.network = false
						} else {
							that.network = true
						}
					}
				})
			},
			onNavigationBarButtonTap(e) {
				console.log("111", this.surveyKh.id)
				if (!this.surveyKh.id) {
					return uni.showToast({
						title: '当前样方没有提交',
						icon: ''
					})
				}
				this.$refs.alertDialog.open()
			},
			async dialogConfirm() {
				let id = this.surveyKh.yfNumber
			
				//删除
				this.surveyKh.action = 'none'
				let userdata = await getInfo("userdata")
				this.userdata = userdata.data
				if (this.network) {
					this.userdata.yf = this.userdata.yf.filter(t => t.yfNumber != id)
					this.userdata.grassType = this.userdata.grassType.filter(t => t.yfNumber != id)
					this.userdata.env = this.userdata.env.filter(t => t.yfNumber != id)
					this.userdata.biomass = this.userdata.biomass.filter(t => t.yfNumber != id)
					this.userdata.subBiomass = this.userdata.subBiomass.filter(t => t.yfNumber != id)
					this.userdata.brush = this.userdata.brush.filter(t => t.yfNumber != id)
					let delinfo = await delYf(id)
					await setInfo("userdata", this.userdata)
			
				} else {
					this.surveyKh.action = 'delete'
					//从缓存中删除
					let yf = this.userdata.yf
					let index = yf.findIndex(t => t.yfNumber == id)
					yf[index] = this.surveyKh
					this.userdata.yf=yf
			
					await setInfo("userdata", this.userdata)
					this.userdata.yf = this.userdata.yf.filter(t => t.id != id)
				}
			
			
				uni.navigateBack({
					delta: 1, //返回层数，2则上上页
				})
				this.$refs.alertDialog.close()
			
			
			},
			dialogClose() {
				this.$refs.alertDialog.close()
			},

			createObject(sq) {
				return {
					"altitude": "",
					"createTime": new Date(),
					"fqqyfzp": "",
					"fqyszwmc": "",
					"fqzbgd": "",
					"fqzbmc": "",
					"fqzbzs": "",
					"fqzzpjgd": "",
					"humidness": "",
					"khyfzp": "",
					"khyszwmc": "",
					"khzbgd": "",
					"khzwmc": "",
					"khzwpjgd": "",
					"khzwzs": "",
					"lat":sq.lat|| "",
					"lon": sq.lon||"",
					"sqyfzp": "",
					"surveyType":sq.surveyType|| "枯黄期",
					"temperature": "",
					"updateTime":  new Date(),
					"ydNumber": sq.ydNumber || "",
					"yfNumber": sq.yfNumber || (new Date()).getFullYear() + "-",
					"zbfqbfl": "",
					"zbgd": "",
					"zbkhbfl": "",
					"zbzgd": "",
					action: sq.action || 'none'
				}
			},
			isFullImg() {
				return new Promise((res) => {
					uni.showModal({
						content: "已经有9张图片了,是否清空现有图片？",
						success: (e) => {
							if (e.confirm) {
								this.imageList = [];
								res(true);
							} else {
								res(false)
							}
						},
						fail: () => {
							res(false)
						}
					})
				})
			},
			async chooseImage() {
				if(this.title!='提交'){
					return
				}
				// #ifdef APP-PLUS
				// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
				if (this.sourceTypeIndex !== 2) {
					let status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
				}
				// #endif

				if (this.imageList.length === 9) {
					let isContinue = await this.isFullImg();
					console.log("是否继续?", isContinue);
					if (!isContinue) {
						return;
					}
				}
				uni.chooseImage({
					sourceType: ['camera', 'album'],
					count: this.imageList.length + this.count[this.countIndex] > 9 ? 9 - this.imageList
						.length : this.count[this.countIndex],
					success: (res) => {
						this.imageList = this.imageList.concat(res.tempFilePaths);
					},
					fail: (err) => {
						console.log("err: ", err);
						// #ifdef APP-PLUS
						if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
							this.checkPermission(err.code);
						}
						// #endif
						// #ifdef MP
						if (err.errMsg.indexOf('cancel') !== '-1') {
							return;
						}
						uni.getSetting({
							success: (res) => {
								let authStatus = false;
								switch (this.sourceTypeIndex) {
									case 0:
										authStatus = res.authSetting['scope.camera'];
										break;
									case 1:
										authStatus = res.authSetting['scope.album'];
										break;
									case 2:
										authStatus = res.authSetting['scope.album'] && res
											.authSetting['scope.camera'];
										break;
									default:
										break;
								}
								if (!authStatus) {
									uni.showModal({
										title: '授权失败',
										content: 'Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting()
											}
										}
									})
								}
							}
						})
						// #endif
					}
				})
			},
			previewImage: function(e) {
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.imageList
				})
			},
			async checkPermission(code) {
				console.log("code",code)
				let type = code ? code - 1 : this.sourceTypeIndex;
				let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
					await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
						'android.permission.READ_EXTERNAL_STORAGE');
			
				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: "没有开启权限",
						confirmText: "设置",
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					})
				}
			
				return status;
			},

			submit(ref) {
				if (this.title == "提交") {
					uni.showLoading({
						title: "提交中",
						mask: true,
						icon: 'loading',
						})
					if (this.network) {
						this.surveyKh.action = 'none'
					} else {
						if (this.surveyKh.action == 'none') {
							this.surveyKh.action = 'edit'
						}
					}
					this.saveLocal().then(res => {

						if (this.network) {
							addOrUpdateYf(this.surveyKh).then(res => {
								uni.hideLoading()
								uni.showToast({
									title: '保存成功',
									icon: 'checkmarkempty'
								})
							})
						} else {
							uni.hideLoading()
							uni.showToast({
								title: '无网络,数据缓存成功',
								icon: 'checkmarkempty'
							})
						}
					})
					this.title = "编辑"
					this.submited = true
					this.isnew=false

				} else {
					this.title = "提交"
					this.isnew=true
				}
			},
			async saveLocal() {
				if (!this.userdata) {
					let userdata = await getInfo("userdata")
					this.userdata = userdata.data
				}
				let that=this
				let peakPeriodzp=[]
				for(const img of this.imageList){
					let saveres=await saveImage(img)
					let upimages={}
					if(that.network){
					let res=await uploadImage(saveres.savedFilePath)
					if(res){
						upimages=JSON.parse(res).data || {}
					}
					}
					let imgInfo={
						name:'枯黄调查',
						uid:upimages.name || (new Date()).getTime(),
						url:upimages.url || null,
						localurl:saveres.savedFilePath,
						id:(new Date()).getTime(),
						action:"edit",
						type:'yf',
						ydNumber:that.surveyKh.ydNumber,
						yfNumber:that.surveyKh.yfNumber
					}
					peakPeriodzp.push(imgInfo)
				}
				this.userdata.files= this.userdata.files.concat(peakPeriodzp)
				this.surveyKh.khyfzp=JSON.stringify(peakPeriodzp)
				
				
				let yf = this.userdata.yf
				if (this.surveyKh.id) {
					let index = yf.findIndex(t => t.id == this.surveyKh.id)
					yf[index] = this.surveyKh
					this.userdata.yf = yf
				} else {
					yf.push(this.surveyKh)
					this.userdata.yf = yf
				}
				await setInfo("userdata", this.userdata)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		position: absolute;
		width: 100vw;
		height: 100vh;

	}

	.example {
		position: absolute;
		width: 100%;
		height: 100vh;
		overflow-y: auto;

		background-color: #fff;
	}

	.form-box {
		padding: 15px;
	}

	.segmented-control {
		margin-bottom: 15px;
	}




	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}

	.totopindex {
		// width: 100%;
		padding: 10rpx;
		margin: 5rpx;
		height: 80rpx;
		border: 1px solid #ccc;

		.btns {
			float: left;
			text-align: right;
			width: 120rpx;
			float: right;
			line-height: 76rpx;
			color: #00aaff;
			text-decoration: underline;

		}
	}
</style>